package com.itheima.test5;

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.UUID;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/*
上传文件的 服务端
 */
public class FuwuClient2 {

    public static void main(String[] args) throws IOException {
        ExecutorService pool = Executors.newCachedThreadPool();
        //创建服务端对象
        ServerSocket ss = new ServerSocket(8888);
        while (true) {
            // 等待建立连接 获取socket对象
             Socket socket = ss.accept();
            ServerThread serverThread = new ServerThread(socket);
            pool.submit(serverThread);
        }


    }
}

class ServerThread implements Runnable{
    private Socket socket;

    public ServerThread(Socket socket) {
        this.socket=socket;
    }

    public void run() {
        BufferedOutputStream bos = null;
        try {
            //获取输入流
            InputStream is = socket.getInputStream();
            BufferedInputStream bis = new BufferedInputStream(is);
            // 创建本地输出流
            bos = new BufferedOutputStream(new FileOutputStream("day16\\copy\\"+ UUID.randomUUID()+".jpg"));
            //读写
            //读写
            int b;
            while ((b = bis.read()) != -1) {
                bos.write(b);
            }

            //向客户端回写数据
            OutputStream os = socket.getOutputStream();
            BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(os));
            writer.write("上传成功");
            writer.newLine();
            writer.flush();
            socket.shutdownOutput();
            //释放资源
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (bos!=null) {
                try {
                    bos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

    }


}
